package servlet;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * Servlet implementation class ImageServlet
 */
@WebServlet("/getImg")
public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		/* Pfad aus der datenabank lesen zur id
		 * bild auslesen von der platte
		 * content tyoe festlegen
		 * bild an den browser senden
		 */
		String ID = request.getParameter("ID");
		
		try{
		
		Class.forName("com.mysql.jdbc.Driver");
	    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/picshare",
	            "root", "");
	    java.sql.PreparedStatement st = con.prepareStatement("select * from bild where bildid=?");
	    st.setString(1, ID);
	    
	    ResultSet rs = st.executeQuery();
		if (rs.next()){
			String link = rs.getString("bildlink");
			response.setContentType("image/jpeg");
			FileInputStream fis = new FileInputStream(new File(link));
			OutputStream out = response.getOutputStream();
			byte b[] = new byte[1];
			int len;
			do {
				len = fis.read(b);
				if (len > 0) {
					out.write(b);
				}
			} while (len > 0);
			fis.close();
			out.close();
			
		}
		}catch(Exception e){
			
		}
		
		
			
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
